package com.wish233.tolerant.impl;

import cn.hutool.core.util.RandomUtil;
import com.wish233.model.register.ServiceMetaInfo;
import com.wish233.model.rpc.RpcRequest;
import com.wish233.model.rpc.RpcResponse;
import com.wish233.proxy.NetClientHandler;
import com.wish233.tolerant.TolerantStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * 转移到其他服务节点 - 容错策略
 *
 * @author WHH
 */
@Slf4j
public class FailOverTolerantStrategy implements TolerantStrategy {

    @Override
    public RpcResponse doTolerant(Map<String, Object> context, Exception e) {
        //从上下文中的
        List<ServiceMetaInfo> infoList = (List<ServiceMetaInfo>)
                context.get("serviceMetaInfos");
        //负载均衡
        RpcRequest request = (RpcRequest) context.get("rpcRequest");
        RpcResponse response;
        try {
            response = NetClientHandler.doRequest(request, infoList.get(RandomUtil.randomInt(infoList.size())));
        } catch (ExecutionException | InterruptedException | TimeoutException ex) {
            throw new RuntimeException(ex);
        }
        return response;
    }
}
